package com.authine.cloudpivot.web.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.web.Utils.ATSSignatureUtil;
import com.authine.cloudpivot.web.Utils.HttpClientUtils;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.model.ats.AtsCloudpivotStateCountModel;
import com.authine.cloudpivot.web.api.model.ats.AtsCloudpivotStateModel;
import com.authine.cloudpivot.web.api.service.AtsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Api(value = "外企德科ATS对接接口", tags = "ats相关接口")
@RestController
@RequestMapping("/api/atsCloudpivot")
@Slf4j
public class AtsToCloudpivotController extends BaseController {

    @Value("${cloudpivotAts.ats_code}")
    private String ats_code;
    @Value("${ats.p_co_id}")
    private String p_co_id;
    @Value("${ats.url}")
    private String url;
    @Value("${ats.user_key}")
    private String user_key;
    @Value("${ats.secretKey}")
    private String secretKey;
    @Value("${ats.email}")
    private String email;
    @Value("${ats.url_append.update}")
    private String updateUrl;
    @Value("${ats.createData.update}")
    private String updateData;

    @Autowired
    private AtsService atsService;

    /**
     * 岗位招聘状态通知接口
     * @param
     * @return
     */
    @ApiOperation(value = "岗位招聘状态通知接口" )
    @PostMapping("/stateNotification")
    public Map<String, String> stateNotification(@RequestBody AtsCloudpivotStateModel model){
        Map<String,String> map = new HashMap<>();
        String code = model.getAts_code();
        if(!ats_code.equals(code)){
            map.put("errcode","500");
            map.put("errmsg","ats_code不正确");
            return map;
        }
        String position_id = model.getPosition_id();
        Long call_time = model.getCall_time();
        Date updateDate = new Date(call_time);
        String state = model.getState();
        log.info(code+"______"+updateDate+"______"+state+"______"+position_id);
        //已完成
        if("2".equals(state)){
            String id = position_id.split("_")[1];
            atsService.closeDemandDetail(id);

            Map<String, Integer> finishedById = atsService.getFinishedById(id);
            //查询总数，如果所有都完成关闭需求
            String parentId = MapUtils.getString(finishedById, "parentId");
            Integer startCount = atsService.findStartCount(parentId);
            if(startCount==0){
                atsService.closeRecruitmentDemand(parentId);
            }
        }
        map.put("errcode","200");
        map.put("errmsg","success");
        return map;
    }

    /**
     * 岗位招聘状态数量通知接口
     * @param
     * @return
     */
    @ApiOperation(value = "岗位招聘状态数量通知接口" )
    @PostMapping("/stateCountNotification")
    public Map<String, String> stateCountNotification(@RequestBody AtsCloudpivotStateCountModel model){
        Map<String,String> map = new HashMap<>();
        String code = model.getAts_code();
        if(!ats_code.equals(code)){
            map.put("errcode","500");
            map.put("errmsg","ats_code不正确");
            return map;
        }
        String position_id = model.getPosition_id();
        Long call_time = model.getCall_time();
        Date updateDate = new Date(call_time);
        String state = model.getState();
        Integer count = model.getCount();
        log.info(code+"______"+updateDate+"______"+state+"______"+position_id+"______"+count);
        //已入职
        if("1".equals(state)){
            String id = position_id.split("_")[1];
            atsService.addDemandDetail(id,count);
            Map<String, Integer> finishedById = atsService.getFinishedById(id);
            Integer demandFor = MapUtils.getInteger(finishedById, "demandFor");
            Integer hasHiredNum = MapUtils.getInteger(finishedById, "hasHiredNum");
            String parentId = MapUtils.getString(finishedById, "parentId");
            if(demandFor != null && hasHiredNum != null){
                if(demandFor <= hasHiredNum){
                    String atsId = MapUtils.getString(finishedById, "atsId");
                    closeAts(atsId,parentId);
                    atsService.closeDemandDetail(id);
                }
            }
            //查询总数，如果所有都完成关闭需求
            Integer startCount = atsService.findStartCount(parentId);
            if(startCount==0){
                atsService.closeRecruitmentDemand(parentId);
            }
        }
        map.put("errcode","200");
        map.put("errmsg","success");
        return map;
    }

    private void closeAts(String atsId,String parentId){
        List<Map<String, Object>> list = new ArrayList<>();
        BizObjectFacade facade = this.getDubboConfigService().getBizObjectFacade();
        BizObjectCreatedModel bizObjectr = facade.getBizObject("recruitmentDemand", parentId);
        Map<String, Object> recruitmentDemand = bizObjectr.getData();
        //招聘需求数据
        List<Map<String,Object>> demandDetails = (List<Map<String, Object>>) recruitmentDemand.get("demandDetails");
        Map<String, Map<String, Object>> projectNameMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("projectName");
        Date demandEndTime = (Date) recruitmentDemand.get("demandEndTime");
        Date demandCreatedTime = (Date) recruitmentDemand.get("demandCreatedTime");
        //岗位jd数据
        Map<String, Map<String, Object>> jdMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("postJD");
        BizObjectCreatedModel bizObjectj = facade.getBizObject("PostJD", MapUtils.getString(jdMap,"id"));
        Map<String, Object> jdData = bizObjectj.getData();
        String jdName = MapUtils.getString(jdData,"jobName");
        String degree = MapUtils.getString(jdData,"degree");
        Integer degreeType = getDegreeType(degree);
        String workyear = MapUtils.getString(jdData,"workyear");
        String[] workyears;
        if(workyear==null||!workyear.contains("-")){
            workyears = new String[]{"0", "1"};
        }else{
            workyears = workyear.split("-");
        }
        String salaryCalculationType = MapUtils.getString(jdData,"salaryCalculationType");
        //同步ats
        for (Map<String, Object> demandDetail : demandDetails) {
            if(!atsId.equals(MapUtils.getString(demandDetail,"atsId"))){
                continue;
            }
            //标签和标签时间
            LocalDateTime now = LocalDateTime.now();
            String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,updateData);
            String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
            //data数据
            Map<String, Object> data = new HashMap<>();
            data.put("queue", "");
            data.put("method", "update");
            data.put("service", "position");
            //params数据
            Map<String, Object> params = new HashMap<>();
            params.put("p_co_id", p_co_id);
            //params.put("email", email);
            //atsID
            params.put("jdId",MapUtils.getString(demandDetail,"atsId"));
            //岗位jd和门店生成
            params.put("third_party_jd_id",MapUtils.getString(demandDetail,"idCode"));
            params.put("create_mode",12);
            //params--jd数据
            Map<String, Object> jd = new HashMap<>();
            String storeName = MapUtils.getString(demandDetail, "storeName");
            if(StringUtils.isNotBlank(storeName)){
                jd.put("name",storeName.concat("--").concat(jdName).concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
            }else{
                jd.put("name",jdName.concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
            }
            jd.put("client_name",MapUtils.getString(projectNameMap,"projectNames"));
            jd.put("order_demand_at",getTenTime(demandCreatedTime.getTime()));
            jd.put("order_start_at",getTenTime((new Date()).getTime()));
            jd.put("actual_canceled_at",getTenTime((new Date()).getTime()));
            jd.put("expect_completed_at",getTenTime(demandEndTime.getTime()));
            BigDecimal demandFor = (BigDecimal) demandDetail.get("demandFor");
            jd.put("number",demandFor.intValue());
            jd.put("salary_type",getSalaryCalculationType(salaryCalculationType));
            jd.put("degree_id",degreeType);
            jd.put("workyear_from",workyears[0]);
            jd.put("workyear_to",workyears[1]);
            jd.put("salary_begin",getCostByM(demandDetail.get("scale")));
            jd.put("salary_end",getCostByM(demandDetail.get("salaryCap")));
            jd.put("requirement",MapUtils.getString(jdData,"jobRequire"));
            jd.put("description",MapUtils.getString(jdData,"jobDuty"));
            jd.put("job_type",getJobType(MapUtils.getString(demandDetail,"jobNature")));
            Map<String, String> workplaces = new HashMap<>();
            Map<String, String> addressMap = new HashMap<>();
            addressMap.put("city",MapUtils.getString(demandDetail,"city"));
            addressMap.put("province",MapUtils.getString(demandDetail,"province"));
            Map<String, String> atsMap = atsService.getAtsMap(addressMap);
            String atsMapId = atsMap.get("id");
            String areas = MapUtils.getString(demandDetail,"areas");
            if(areas == null){
                areas = "";
            }
            workplaces.put("city_id",atsMapId);
            workplaces.put("address",areas.concat(MapUtils.getString(demandDetail,"address")));
            jd.put("workplaces",workplaces);
            List<String> advantages = new ArrayList<>();
            jd.put("advantages",advantages);
            jd.put("state",2);
            jd.put("actual_completed_at",getTenTime((new Date()).getTime()));
            params.put("jd",jd);
            //总数据
            Map<String, Object> map = new HashMap<>();
            map.put("call_time",call_time);
            map.put("signature",signature);
            map.put("userKey",user_key);
            map.put("data",data);
            map.put("params",params);
            String s = JSON.toJSONString(map);
            log.info("参数==" + s);
            String post = HttpClientUtils.jsonPost(url+updateUrl, JSONObject.parseObject(s));
            log.info(post);
            Map<String, Object> postMap = JSON.parseObject(post, Map.class);
            list.add(postMap);
        }
    }

    private Integer getCostByM(Object costo){
        if(costo==null){
            return 0;
        }
        BigDecimal cost = (BigDecimal) costo;
        BigDecimal costM = cost.multiply(BigDecimal.valueOf(100)).setScale(0);
        return Integer.valueOf(costM.toString());
    }

    private Long getTenTime(long time){
        return time / 1000;
    }

    private Integer getSalaryCalculationType(String type){
        if(type==null){
            return 0;
        }
        switch (type){
            case "面议":
                return 0;
            case "年薪":
                return 1;
            case "月薪":
                return 2;
            case "日薪":
                return 3;
            case "时薪":
                return 4;
            case "周薪":
                return 5;
            case "双周薪":
                return 6;
            default:
                return 0;
        }
    }

    private Integer getJobType(String type){
        if(type==null){
            return 1;
        }
        switch (type){
            case "全职":
                return 1;
            case "兼职":
                return 2;
            case "实习生":
                return 3;
            default:
                return 1;
        }
    }

    private Integer getDegreeType(String type){
        if(type==null){
            return 1;
        }
        switch (type){
            case "本科":
                return 1;
            case "硕士":
                return 2;
            case "博士":
                return 3;
            case "专科":
                return 4;
            case "博士后":
                return 10;
            case "初中":
                return 86;
            case "职高":
                return 87;
            case "高中":
                return 89;
            case "中专":
                return 90;
            case "中技":
                return 91;
            case "专升本":
                return 92;
            default:
                return 1;
        }
    }
}
